<?php

namespace addons\wechatlogin;

use think\Addons;
use think\Cookie;
use think\Session;

/**
 * 插件
 */
class Wechatlogin extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        return true;
    }

    public function actionBegin()
    {
        $request = request();
        //判断是否是前端登录页面
        if ($request->module() == 'index'
            && $request->controller() == 'User'
            && $request->action() == 'login') {

            //判断是否存在之前的cookie
            if (Cookie::has('uid') && Cookie::has('token')) {
                $url = $request->request('url', '', 'trim');
                $url = $url ? $url : url('user/index');
                header('Location: ' . $url);
            } else {
                $this->frontendNologin($request);
            }
        }
    }

    public function frontendNologin($request)
    {
        $cfg = $this->getConfig();
        if ($cfg['onlywechat'] == 0) {
            return;
        } else {
            if ($cfg['ser_cli'] == 1) {
                //这里主接微信公众号 直接跳转地址
                $url = addon_url('third/index/connect', [':platform' => 'wechat', 'url' => $request->url(true)]);
                header('Location: ' . $url);
                exit();
            } else {
                //这里是间接跳转公众号，就是通过其他的fa平台的 微信登录插件 获得用户信息

                //Session 存储 现在的网页地址
                Session::set("redirecturl_client", $request->url(true));

                //跳转
                $url = $cfg['serve_path'];
                $url .= addon_url('wechatlogin/third/connect', ['pw' => $cfg['password'], 'url' => base64_encode(addon_url('wechatlogin/third/callback_client', null, true, true))]);
                header('Location: ' . $url);
                exit();
            }
        }
    }
}
